<?php
namespace WDB\Query\Element;
use WDB,
    WDB\Exception;
/**
 * Table source with an alias.
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 *
 * @property-read iTableSource $tableSource
 * @property-read string $alias
 */
class AliasedTableSource extends WDB\Structure\Structure implements iTableSource
{
    /**
     * @param iTableSource|WDB\Query\Select table source
     * @param string alias
     * @throws WDB\Exception\BadArgument
     */
    public static function create($tableSource, $alias)
    {
        if (!$tableSource instanceof WDB\Query\Select && !$tableSource instanceof iTableSource)
        {
            throw new Exception\BadArgument("table source must be Select or iTableSource");
        }
        return new self (array('tableSource'=>$tableSource, 'alias'=>$alias));
    }

    public function toSQL(WDB\SQLDriver\iSQLDriver $driver)
    {
        return $driver->tosql_aliasedTableSource($this);
    }

    public function alias($alias)
    {
        return AliasedTableSource::create($this->tableSource, $alias);
    }
}
